package org.footballmanager.pandafootball.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.annotation.SystemServiceLog;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.common.exception.ExceptionEnum;
import org.footballmanager.pandafootball.common.exception.MyException;
import org.footballmanager.pandafootball.system.dao.PhotoDao;
import org.footballmanager.pandafootball.system.domain.FootGj;
import org.footballmanager.pandafootball.system.domain.FootPerson;
import org.footballmanager.pandafootball.system.domain.FootQd;
import org.footballmanager.pandafootball.system.domain.Photo;
import org.footballmanager.pandafootball.system.domain.enums.FL;
import org.footballmanager.pandafootball.system.form.impl.PhotoSearchForm;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

@Slf4j
@Service
public class PhotoServiceImpl extends ServiceImpl<Photo> implements PhotoService {
    @Autowired
    private PhotoDao photoDao;
    @Autowired
    private FootPersonService footPersonService;
    @Autowired
    private FootGjService footGjService;
    @Autowired
    private FootQdService footQdService;
    @Autowired
    private ImageUpload imageUploader;

    /**
     * 保存图像信息
     *
     * @param t       实体类
     * @param request 请求
     * @return 是否成功
     */
    @Override
    @Transactional
    public int save(Photo t, HttpServletRequest request) {
        super.save(t, request);
        updateDatabase(t, request);
        return t.getId().intValue();
    }

    /**
     * 更新数据库信息
     *
     * @param t       图像实体类
     * @param request 请求
     */
    private void updateDatabase(Photo t, HttpServletRequest request) {
        if (t.getType().equals(FL.GAMER)) {
            processGamer(t, request);
        } else if (t.getType().equals(FL.CLUBBIG) || t.getType().equals(FL.CLUBSMALL)) {
            processClub(t, request);
        } else if (t.getType().equals(FL.FLAGBIG) || t.getType().equals(FL.FLAGSMALL)) {
            processFlag(t, request);
        }
    }

    /**
     * 处理球员图像信息
     *
     * @param t       图像实体类
     * @param request 请求
     */
    private void processGamer(Photo t, HttpServletRequest request) {
        FootPerson fp = footPersonService.findByQybm(t.getName());
        if (fp != null) {
            fp.setZp(t.getId());
            footPersonService.updateNotNull(fp, request);
        }
    }

    /**
     * 处理球队图像信息
     *
     * @param t       图像实体类
     * @param request 请求
     */
    private void processClub(Photo t, HttpServletRequest request) {
        FootQd fq = footQdService.findByName(t.getName());
        if (fq == null) {
            return;
        }
        if (t.getType().equals(FL.CLUBBIG)) {
            fq.setLogo(t.getId());
        } else {
            fq.setSlt(t.getId());
        }
        footQdService.updateNotNull(fq, request);
    }

    /**
     * 处理国旗图像信息
     *
     * @param t       图像实体类
     * @param request 请求
     */
    private void processFlag(Photo t, HttpServletRequest request) {
        FootGj fq = footGjService.findByName(t.getName());
        if (fq == null) {
            return;
        }
        if (t.getType().equals(FL.FLAGBIG)) {
            fq.setLogo(t.getId());
        } else {
            fq.setSlt(t.getId());
        }
        footGjService.updateNotNull(fq, request);
    }

    /**
     * 根据国籍找对应的小图片信息
     *
     * @param gj 国籍
     * @return 小图片信息
     */
    @Override
    public Photo findNationSmall(String gj) {
        Example example = new Example(Photo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name", gj);
        criteria.andEqualTo("type", FL.FLAGSMALL);
        criteria.andEqualTo("delFlag", 0);
        return this.findByExample(example);
    }

    /**
     * 根据国籍找对应的大图片信息
     *
     * @param gj 国籍
     * @return 大图片信息
     */
    @Override
    public Photo findNationBig(String gj) {
        Example example = new Example(Photo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name", gj);
        criteria.andEqualTo("type", FL.FLAGBIG);
        criteria.andEqualTo("delFlag", 0);
        return this.findByExample(example);
    }

    /**
     * 根据类型查找图像
     *
     * @param type 类型
     * @return 图像集合
     */
    @Override
    public List<Photo> findByType(FL type) {
        Example example = new Example(Photo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("type", type);
        criteria.andEqualTo("delFlag", 0);
        return this.findall(example);
    }

    /**
     * 查询
     *
     * @param entityname      实体类名
     * @param map             参数
     * @param photoSearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, PhotoSearchForm photoSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), photoSearchForm);
        Page<Photo> page = PageHelper.startPage(photoSearchForm.getPageIndex(), photoSearchForm.getPageSize());
        List<Photo> list = this.findall(photoSearchForm.buildSearchCommond());
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }

    /**
     * 删除所有
     *
     * @param photoSearchForm 条件
     * @param request         请求
     */
    @Override
    public void deleteAll(PhotoSearchForm photoSearchForm, HttpServletRequest request) {
        if (photoSearchForm.getSelectIds() != null) {
            String[] result = photoSearchForm.getSelectIds().split(Constants.COMMA);
            for (String id : result) {
                this.delete(Long.parseLong(id), request);
            }
        }
    }

    /**
     * 保存图像
     *
     * @param photo   图像实体类
     * @param img     上传文件
     * @param request 请求
     */
    @Override
    public void save(@Valid Photo photo, MultipartFile img, HttpServletRequest request) {
        processPhoto(photo, img);
        photo.setUrl(imageUploader.addPhoto(img, request, photo.getType()));
        this.save(photo, request);
    }

    /**
     * 处理图像
     *
     * @param photo 图像信息
     * @param img   上传文件
     */
    @Override
    public void processPhoto(Photo photo, MultipartFile img) {
        String allname;
        if (img != null) {
            allname = img.getOriginalFilename().substring(img.getOriginalFilename().lastIndexOf("\\") + 1);
        } else {
            return;
        }
        if (null != photo.getImg() && photo.getImg().length != 0) {
            String[] type = allname.split("[.]");
            photo.setDx((long) photo.getImg().length);
            photo.setExt(type[type.length - 1]);
            if (photo.getType().equals(FL.FLAGBIG) || photo.getType().equals(FL.FLAGSMALL)) {
                try {
                    photo.setName(URLDecoder.decode(type[0], "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new MyException(ExceptionEnum.CODEEXCEPTION, e);
                }
            } else {
                photo.setName(type[0]);
            }
        }
    }

    /**
     * 更新图像
     *
     * @param photo   图像实体类
     * @param img     上传文件
     * @param request 请求
     */
    @Override
    public void update(@Valid Photo photo, MultipartFile img, HttpServletRequest request) {
        processPhoto(photo, img);
        photo.setUrl(imageUploader.upload(img, request, photo.getType()));
        super.updateNotNull(photo, request);
    }

    /**
     * 保存多张图像
     *
     * @param fl      分类
     * @param files   上传的文件们
     * @param request 请求
     */
    @Override
    public void saveMore(FL fl, List<String> files, HttpServletRequest request) throws UnsupportedEncodingException {
        if (files == null || files.isEmpty()) {
            return;
        }
        for (String fileName : files) {
            File file = new File(ClassUtils.getDefaultClassLoader().getResource("").getPath() + fileName);
            Photo photo = new Photo();
            photo.setType(fl);
            String[] type = file.getName().split("[.]");
            photo.setDx(file.getUsableSpace());
            photo.setExt(type[type.length - 1]);
            if (fl.equals(FL.FLAGBIG) || fl.equals(FL.FLAGSMALL)) {
                photo.setName(URLDecoder.decode(type[0], "UTF-8"));
            } else {
                photo.setName(type[0]);
            }
            photo.setUrl(fileName);
            this.save(photo, request);
        }
        files.clear();
    }

    /**
     * 添加文件到文件列表里
     *
     * @param file    上传文件
     * @param type    类型
     * @param files   文件列表
     * @param request 请求
     */
    @Override
    public void addMore(MultipartFile file, FL type, List<String> files, HttpServletRequest request) {
        files.add(imageUploader.addPhoto(file, request, type));
    }

    /**
     * 查找图像
     *
     * @param photoSearchForm 添加
     * @param id              主键
     * @param index           正反向
     */
    @Override
    public Photo find(PhotoSearchForm photoSearchForm, Long id, Integer index) {
        List<Photo> viewList = this.findall(photoSearchForm.buildSearchCommond());
        int c = 0;
        for (int i = 0; i < viewList.size(); i++) {
            if (viewList.get(i).getId().equals(id)) {
                c = i;
            }
        }
        c += index;
        if (c < 0) {
            c = 0;
        }
        if (c >= viewList.size()) {
            c = viewList.size() - 1;
        }
        return viewList.get(c);
    }

    /**
     * 删除图像记录
     *
     * @param id      参数
     * @param request 参数
     * @return 返回值
     */
    @Override
    @Transactional
    @SystemServiceLog(description = "删除记录")
    public int delete(Serializable id, HttpServletRequest request) {
        imageUploader.delete(photoDao.selectByPrimaryKey(id), request);
        return super.delete(id, request);
    }
}
